const http=require('http');
const fs=require('fs');
const path=require('path');
const { DefaultDeserializer } = require('v8');

var pagePath=path.join(__dirname,'/index.html');
var iconPath=path.join(__dirname,'/1.png');
var dirPath=path.join(__dirname,'/filedir');

//拆解url
function parseUrl(urlStr){
    var index=urlStr.indexOf('?');
    var pathName='';
    var args='';
    var argObj={};
    if(index==-1){
        var pathName=urlStr;
    }else{
        var pathName=urlStr.slice(0,index);
        args=urlStr.slice(index+1);
        var argArr=args.split('&');
        for(var i=0;i<argArr.length;i++){
            argObj[argArr[i].split('=')[0]]=argArr[i].split('=')[1];
        }
    }
    return {
        pathName:pathName,
        argObj:argObj
    }
}

function createFileTime(time){
    var date=new Date(time);
    var year=date.getFullYear();
    var month=date.getMonth()+1;
    var day=date.getDate();
    var hour=date.getHours();
    var minute=date.getMinutes();
    return `${year}-${month}-${day} ${hour}:${minute}`;
}

function delDir(dirPath){
    var files=fs.readdirSync(dirPath);
    for(var i=0;i<files.length;i++){
        var filePath=path.join(dirPath,'/'+files[i]);
        var fileObj=fs.statSync(filePath);
        if(fileObj.isFile()){
            fs.unlinkSync(filePath);
        }else{
            delDir(filePath);
        }
    }
    fs.rmdirSync(dirPath);
}

//对各种不同的请求进行处理
function router(urlObj,req,res){
    if(urlObj.pathName.indexOf('.png')>0 || urlObj.pathName.indexOf('.jpg')>0){
        urlObj.pathName="getimgdata";  //请求图片资源时将pathName统一
    }
    switch(urlObj.pathName){
        case '/':
            showIndex(res);
            break;
        case 'getimgdata':
            resImage(res);
            break;
        case '/getlist':
            showList(res);
            break;
        case '/del':
            deleteFile(urlObj.argObj,res);
    }
}

function showIndex(res){
    var fileContent=fs.readFileSync(pagePath);
    res.writeHead(200,{'content-type':'text/html;charset=utf-8'})  //让浏览器按html代码格式响应
    res.write(fileContent);
    res.end();  //结束响应
}

function resImage(res){
    var imgContent=fs.readFileSync(iconPath);
    res.writeHead(200,{'content-type':'image/png'});
    res.write(imgContent);
    res.end();
}

function showList(res){
    var files=fs.readdirSync(dirPath);
    var fileList=[];
    for(var i=0;i<files.length;i++){
        var filePath=path.join(dirPath,'/'+files[i]);
        var fileObj=fs.statSync(filePath);
        var obj={};
        obj.fileName=files[i];
        obj.fileTime=createFileTime(fileObj.ctimeMs);
        obj.fileSize=fileObj.size;
        obj.fileType=fileObj.isFile()?'file':'folder';
        obj.fileTemp=fileObj.ctimeMs;
        fileList.push(obj);
    }
    //不能直接响应数组,要转换为json数据格式
    var jsonStr=JSON.stringify(fileList);
    res.writeHead(200,{'content-type':'text/plain'});
    res.write(jsonStr);
    res.end();  
}

function deleteFile(argObj,res){
    var delId=argObj.delId;
    var files=fs.readdirSync(dirPath);
    for(var i=0;i<files.length;i++){
        var filePath=path.join(dirPath,'/'+files[i])
        var fileObj=fs.statSync(filePath);
        if(delId.indexOf(fileObj.ctimeMs)>0){
            if(fileObj.isFile()){
                fs.unlinkSync(filePath);
            }else{
                delDir(filePath);
            }
            res.end('success');
        }
    }

}
http.createServer((req,res)=>{
    //可以使用res.write(bodydata) 或 readable.pipe(res);
    // http://localhost:8081/pathname?delId=2345677643&pageId=87543217987
    //req.url指端口或者域名之后的部分
    var urlStr=req.url;
    var urlObj=parseUrl(urlStr);
    // console.log(urlObj);
    router(urlObj,req,res);
}).listen(8081);

console.log("server is listening 8081");